package organizer.hb;

import java.io.File;
import organizer.FileMetadata;
import organizer.FileUtils;
import organizer.IFileMetadata;

/**
 * Stores/Retrieves metadata via dao.
 * 
 * @author dawong
 */
public class FileRepository {
    
    private MetadataDao dao;

    public FileRepository(MetadataDao dao) {
        this.dao = dao;
    }

    public IFileMetadata getMetadata(File file) {
        if (!file.exists())
            return null;
        String path = file.getAbsolutePath();
        IFileMetadata ret = dao.getMetadata(path);
        if (ret != null) {
            if (ret.getLength() != file.length() ||
                    ret.getModifiedDate() != file.lastModified()) {
                // file has changed
                // clear hash
                FileMetadata meta = new FileMetadata(path, file.length(), file.lastModified());
                dao.update(meta);
                ret = meta;
            }
        } else {
            // new file
            FileMetadata meta = new FileMetadata(path, file.length(), file.lastModified());
            dao.add(meta);
            ret = meta;
        }
        return ret;
    }

    public void updateMetadata(IFileMetadata metadata) {
        dao.update(metadata);
    }

    public String getHash(File file) {
        if (file.exists()) {
            return FileUtils.hash(file);
        }
        return null;
    }

}
